var express		= require('express');
var app = require('express')(),
	server = require('http').createServer(app);
var fs			= require("fs");
var bodyParse	= require('body-parser');
var path		= require('path');
var url			= require("url");
var querystring	= require("querystring");
var tiMsg = require('./routes/TiMsg');

// http://192.168.1.116:3000/
// http://192.168.1.116:3000/?selfid=1234567&val=userManager
// http://192.168.1.116:3000/?selfid=1234567&val=clubManager

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8080});
// 连接池
var clients = {};

wss.on('connection', function(ws) {
	// 收到连接信息
    ws.on('message', function(message) {
		message = JSON.parse(message);
		if (message.type === "REGISTER") {
			clients[message.selfid] = ws;
			console.log(message.selfid,'拿到什么');
		}
    });

    // ws.on('close', function(message) {
    //     // 连接关闭时，将其移出连接池
    //     clients = clients.filter(function(ws1){
    //         return ws1 !== ws
    //     })
    // });
});

app.use(bodyParse.urlencoded({extended:false}));
// 通过这句话，可以将一个工具类的js脚本放到public文件夹中 
app.use(express.static(path.join(__dirname, 'public')));


// 处理get充值订单初始页请求
app.get('/',function(req,res){
	// 获取返回的url对象的query属性值 
	var arg = url.parse(req.url).query;
	if(arg) {
		//将arg参数字符串反序列化为一个对象
		var params = querystring.parse(arg);
		console.log("params = ",params);
		// 请求的方式
		console.log("method = " + req.method);
		// 请求的url
		console.log("url = " + req.url);
		if(params.val == "userManager") {
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<script>var selfid=" + params.selfid + "</script>";
			fs.readFile("./public/userManager.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('玩家管理+++++++++++++++++++',params.selfid);
		}else if(params.val == "clubManager") {
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<script>var selfid=" + params.selfid + "</script>";
			fs.readFile("./public/clubManager.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('公会管理+++++++++++++++++++',params.selfid);
		}
	}else {
		res.sendfile('./public/managerLogin.html');
	}
});

// 客服登陆时触发
app.post('/managerLogin', async (req,res) => {
	console.log(req.body.id,req.body.password,'managerLogin来了');
	let rows = await tiMsg.matching(req.body.id);
	if(rows.length >= 1) {
		if(req.body.password == rows[0].password) {
			res.json({"status":"success",msg:req.body.id});
			console.log('login有这个人，加载聊天界面');
		}else {
			res.json({"status":"fail",msg:'用户名或密码错误，登陆失败1'});
			console.log('用户名或密码错误，登陆失败');
		}
	}else {
		res.json({"status":"fail","msg":'用户名或密码错误，登陆失败2'});
		console.log('用户名或密码错误，登陆失败');
	}
});

// 向数据库发起请求 查询玩家账户
app.post('/user_data', async (req,res) => {
	console.log(req.body.userID,'userdata出去');
	let rows = await tiMsg.get_user_data(req.body.userID);
	if(rows.length >= 1) {
		res.json({"status":"success",user_data:rows});
		console.log(rows,'数据回来了');
	}else {
		res.json({"status":"fail",msg:'无数据'});
		console.log(rows,'无数据');
	}
});

// 向数据库发起请求 查询公会账户
app.post('/club_data', async (req,res) => {
	console.log(req.body.clubID,'clubdata出去');
	let rows = await tiMsg.get_club_data(req.body.clubID);
	if(rows.length >= 1) {
		res.json({"status":"success",club_data:rows});
		console.log(rows,'数据回来了');
	}else {
		res.json({"status":"fail",msg:'无数据'});
		console.log(rows,'无数据');
	}
});

server.listen(3000);
